<template>
  <div class="select-group" @click="handleClick" v-if="dataSource.length >0">
    <span class="select-title" v-if="title">{{ title }}:</span>
    <span class="select-button" v-for="item in dataSource" :data-value="item[valueKey]">
      {{ item[labelKey] }}
    </span>
  </div>
</template>
<script lang="ts" setup>
import { type PropType} from 'vue'

type modeType = 'radio' | 'checkbox'
interface OptionType {
  [key: string]: string | number | boolean
}

const value = defineModel<string[]>('value',{default: ()=>[]})
const props = defineProps({
  dataSource: {type: Array as PropType<OptionType[]>, default: []},
  mode: {type: String as PropType<modeType>, default: 'radio'},
  labelKey: {type: String, default: 'label'},
  valueKey: {type: String, default: 'value'},
  title: {type: String, default: ''}
})
const handleClick = (e: Event) => {
  const target = e.target as HTMLElement
  if (!target.classList.contains('select-button')) return
  
  const clickedValue = target.dataset.value
  if (!clickedValue) return

  if(props.mode === 'radio') {
    value.value = [clickedValue]
    target.parentElement?.querySelectorAll('.select-button').forEach(item => {
      item.classList.remove('select-active')
    })
    target.classList.add('select-active')
  } else {
    target.classList.toggle('select-active')
    const index = value.value.indexOf(clickedValue)
    if(index === -1) {
      value.value.push(clickedValue)
    } else {
      value.value.splice(index, 1)
    }
  }
}
</script>
<style scoped>
  .select-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.select-button {
  padding: 3px 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  cursor: pointer;
}
.select-button.select-active ,
.select-button:hover {
  background-color: #e6f4ff;
  color: #1677ff;
  transition: all 0.3s ease;
}
.select-title {
  padding: 3px 0;
  color: #666;
}
</style>